package com.summer.service;

import com.alibaba.fastjson.JSON;
import com.summer.dao.StudentDao;
import com.summer.dao.UserDao;
import com.summer.bean.Student;
import com.summer.bean.User;
import com.summer.result.PersonalDetailResult;
import com.summer.result.Result;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;

/**
 * Created by IntelliJ IDEA.
 * Description:
 * User: 35391
 * Package: com.summer.service
 * Date: 2025/3/23
 * Time: 下午3:41
 * Version: 1.0
 */
@WebServlet({"/user/login", "/user/exit", "/user/register", "/user/saveStudentInformation"})
public class UserService extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Result<Object> result = new Result<>();
        String path = request.getServletPath();
        if ("/user/login".equals(path)) {
            result = doLogin(request, response);
        } else if ("/user/exit".equals(path)) {
            result = doExit(request, response);
        }else if ("/user/register".equals(path)){
            result = doRegister(request, response);
        }else if ("/user/saveStudentInformation".equals(path)){
            result = doSaveStudentInformation(request, response);
        }
        // 统一处理响应
        if (result != null) {
            String jsonResult = JSON.toJSONString(result);
            response.setContentType("application/json;charset=UTF-8");
            PrintWriter out = response.getWriter();
            out.print(jsonResult);
            out.flush();
            out.close();
        }
    }

    private Result<Object> doSaveStudentInformation(HttpServletRequest request, HttpServletResponse response) {
        try {
//            System.out.println("doSaveStudentInformation");
            boolean isExist = true;
            response.setContentType("application/json;charset=UTF-8");
            PersonalDetailResult personalDetailResult = new PersonalDetailResult();
            Student student = StudentDao.selectBySno(request.getParameter("Sno"));
            if(student == null){
                student = new Student();
                isExist = false;
            }
            if(!request.getParameter("Sno").matches("^S\\d{3}$")){
                personalDetailResult.setTargetPage("setPersonalInformation");
                return Result.success("学号格式错误", personalDetailResult);
            }
            if("false".equals(request.getParameter("isExisting")) && request.getParameter("Sno") != null && request.getParameter("Sno").equals(student.getSno())){
                personalDetailResult.setTargetPage("setPersonalInformation");
                return Result.success("学号已存在", personalDetailResult);
            }
            if(request.getParameter("Sname").isEmpty() || request.getParameter("Sdept").isEmpty() || request.getParameter("Address").isEmpty() || request.getParameter("Gender").isEmpty() || request.getParameter("DOB").isEmpty() || request.getParameter("Telephone").isEmpty() || request.getParameter("Degree").isEmpty()){
               personalDetailResult.setTargetPage("setPersonalInformation");
                return Result.success("请填写完整信息", personalDetailResult);
            }
            if(!request.getParameter("Gender").equals("男") && !request.getParameter("Gender").equals("女")){
                personalDetailResult.setTargetPage("setPersonalInformation");
                return Result.success("性别只能为‘男’或‘女’", personalDetailResult);
            }
            student.setSno(request.getParameter("Sno"));
            student.setSname(request.getParameter("Sname"));
            student.setSdept(request.getParameter("Sdept"));
            student.setAddress(request.getParameter("Address"));
            student.setGender(request.getParameter("Gender"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            student.setDOB(sdf.parse(request.getParameter("DOB")));
            student.setTelephone(request.getParameter("Telephone"));
            student.setDegree(request.getParameter("Degree"));
            int res = 0;
            if(isExist){
                res += StudentDao.upDateBySno(student);
            }else{
                res += StudentDao.insert(student);
            }
            String username = request.getParameter("username");
            res += UserDao.updateSnoByUsername(student.getSno(), username);
//            System.out.println("student=" + student);
            if(res != 2){
                return Result.error("保存失败");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return Result.success();
    }

    private Result<Object> doRegister(HttpServletRequest request, HttpServletResponse response) {
        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        response.setContentType("application/json;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = new User();
        user = UserDao.selectByUsername(username);
        if (user.getId() != null) {
            return Result.error("用户名已存在");
        }
        user.setUsername(username);
        user.setPassword(password);
        UserDao.insert(user);
        return Result.success();
    }

    protected Result<Object> doExit(HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        response.setContentType("application/json;charset=UTF-8");
        HttpSession session = request.getSession(false);
        if(session != null){
            session.invalidate();
            Cookie[] cookies = request.getCookies();
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName()) || "password".equals(cookie.getName())){
                    cookie.setMaxAge(0);
                    cookie.setPath(request.getContextPath());
                    response.addCookie(cookie);
                }
            }
            //TODO 跳转:162
            response.sendRedirect(request.getContextPath());
        }
        return Result.success();
    }


    protected Result<Object> doLogin(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        User user = UserDao.selectByUsernameAndPassword(username, password);
//        System.out.println(user);
        if(user.getId() != null){
            HttpSession session = request.getSession();
            session.setAttribute("username", username);
            if("1".equals(request.getParameter("flag"))){
                Cookie cookie1 = new Cookie("username", username);
                Cookie cookie2 = new Cookie("password", password);
                cookie1.setMaxAge(60 * 60 * 24 * 10);
                cookie2.setMaxAge(60 * 60 * 24 * 10);
                cookie1.setPath(request.getContextPath());
                cookie2.setPath(request.getContextPath());
                response.addCookie(cookie1);
                response.addCookie(cookie2);
//                System.out.println(cookie1);
//                System.out.println(cookie2);
            }
        }else {
            return Result.error("登录失败");
        }
        return Result.success(username);
    }
}
